package com.dvg.comms;

import java.io.IOException;

public class CommsManager 
{
	public static final int CommsErrorCouldNotConnect = -1001;
	public static final int CommsErrorDownloadFailed = -1002;
	
	private static CommsManager Instance = null;
	
	private CommsManager()
	{
	}
	
	public static CommsManager getInstance()
	{
		if(Instance == null)
		{
			Instance = new CommsManager();
		}
		
		return Instance;
	}
	
	public void getDataAndCallback(String aUrl, CommsListener aListener)
	{
		Thread t = new Thread(new GetDataAndCallback(aUrl, aListener));
		t.start();
	}
	
	// Used for getting beacons where we only need to download the data
	// and not actually use it
	public void getData(String aUrl)
	{
		Thread t = new Thread(new GetData(aUrl));
		t.start();
	}
	
	private class GetDataAndCallback implements Runnable
	{
		String iUrl;
		CommsListener iListener;
		
		public GetDataAndCallback(String aUrl, CommsListener aListener)
		{
			iUrl = aUrl;
			iListener = aListener;
		}
		
		public void run()
		{
			byte[] data = null;
			CommsEngine iCommsEngine = new CommsEngine();
			
			// Open connection
			try
			{
				iCommsEngine.openConnection(iUrl);
			}
			catch(IOException e)
			{
				iListener.notifyCommsError(CommsErrorCouldNotConnect);
				return;
			}
			
			// get data
			try
			{
				data = iCommsEngine.getData();
			}
			catch(IOException e)
			{							
				// close connection
				iCommsEngine.closeConnection();
				iListener.notifyCommsError(CommsErrorDownloadFailed);
				return;
			}
			
			// close connection
			iCommsEngine.closeConnection();
	
			// callback listener with data
			iListener.notifyCommsSuccess(data);
		}
	}
	
	private class GetData implements Runnable
	{
		String iUrl;
		
		public GetData(String aUrl)
		{
			iUrl = aUrl;
		}
		
		public void run()
		{
			CommsEngine iCommsEngine = new CommsEngine();
			
			// open connection
			try
			{
				iCommsEngine.openConnection(iUrl);
				byte[] data = iCommsEngine.getData();
			}
			catch(IOException e)
			{
				// No listener so fail silently
			}

			// close connection
			iCommsEngine.closeConnection();
		}
	}
}
